﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using XfTechOAWeb.Data;
using XfTechOAWeb.Models;
using XfTechOAWeb.Infrastructure.Utilities;
using Microsoft.Extensions.Configuration;
using Microsoft.Data.SqlClient;
using Dapper;

namespace XfTechOAWeb.EFCore
{
    /// <summary>
    /// 此仓储类 演示Dapper的使用
    /// </summary>
    public class TodoItemRepository : ITodoItemRepository
    {
        /// <summary>
        /// 连接字符串
        /// </summary>
        private readonly string _strConnectionString = string.Empty;
        
        /// <summary>
        /// 构造函数
        /// </summary>
        public TodoItemRepository()
        {
            _strConnectionString = AppConfigurtaionServices.Configuration.GetConnectionString("sqlserver");
        }

        /// <summary>
        /// 获取某用户的待办事项
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<IEnumerable<TodoItem>> GetListAsync(int userId)
        {
            //using语句块--自动回收资源 
            using(var conn = new SqlConnection(_strConnectionString))
            {
                string sql = "select top 10 * from TodoItems where CreatedUserID=@UserId order by CreatedTime desc";
                return await conn.QueryAsync<TodoItem>(sql, new { UserId = userId });
            } //出了using语句块之后，conn对象会被自动回收
        }

        /// <summary>
        /// 添加待办事项
        /// </summary>
        /// <param name="todoItem"></param>
        /// <returns></returns>
        public async Task<int> InsertAsync(TodoItem todoItem)
        {
            using (var conn = new SqlConnection(_strConnectionString))
            {
                string sql = "insert into TodoItems(Text,Status,CreatedTime,CreatedUserID) " +
                                      "values(@Text,@Status,@CreatedTime,@CreatedUserID)";
                return await conn.ExecuteAsync(sql, todoItem);
            }
        }
    }
}
